<template>

  <div v-if="isShow" style="height: 100%">
    <DocumentEditor
        id = "docEditor"
        :documentServerUrl = "serverUrl"
        :config = "config"
        :events_onDocumentReady = "onDocumentReady"
        :events_onRequestSharingSettings = "onRequestSharingSettings"
    />
  </div>

  <cooperate-authority v-model:dialog-drawer="cooperateVisible" :file-log-id="currentFileLogId" />

</template>

<script>
import {onMounted, reactive, ref, toRefs} from "vue";
import {DocumentEditor} from "@onlyoffice/document-editor-vue";
import {cooperateStates} from '/@/stores/space/cooperate'
import Cookies from "js-cookie";
import {isMobile} from "../../home/component/lib/scroll";
import {useRouter} from 'vue-router'
import {getByFileLogId} from "../../../api/sys/cooperate";
import CooperateAuthority from "../components/CooperateAuthority.vue";
import {getDocumentType} from '/@/utils/common'
import {getCurrentUserInfo} from "../../../api/sys/user";
import { ElMessageBox } from 'element-plus'
import {useUserInfo} from '/@/stores/userInfo'

export default {
  name: "CollaborativeDocument",
  components: {
    DocumentEditor,
    CooperateAuthority
  },
  props: {
    fileData: {
      type: Object,
      default() {
        return {}
      }
    },
  },
  setup(props, context) {
    const { fileData } = toRefs(props)  //弃用
    const router = useRouter()
    let apiUrl = ref("")
    let isEdit = ref(false)
    let mode = ref("view")
    const storesCooperate = cooperateStates()
    const storesUserInfo = useUserInfo()
    const state = reactive({
      isShow:false,
      cooperateVisible:false,
      currentFileLogId:null,
      config: {},
      editor:null,
      invite:[],
      fileData:{},
      noAccess:false,
      serverUrl:import.meta.env.VITE_DOCUMENT_API_URL,
      docAuthority: 3, //默认3->私密的
    })
    //加载完成回调
    const onDocumentReady = (editor) => {
      console.log("我准备好了")
      state.editor = editor;
    }
    //更改访问权限
    const onRequestSharingSettings = () => {
      if (storesUserInfo.userInfos.id === state.fileData.userId){
        state.cooperateVisible = true
      }else{
        ElMessageBox.confirm(
            '当前文档权限为:' + returnDocAuthority(),
            '无修改权限',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
        )
      }
    }
    //返回文档权限中文数据 等待字典管理
    const returnDocAuthority = () => {
      switch (state.docAuthority){
        case 0: return "公共读写"
        case 1: return "公共读"
        case 2: return "仅邀请"
        case 3: return "私密的"
      }
    }
    //判断用户权限
    const userAuthority = () => {
      let data
      const storesUserInfo = useUserInfo() //目前是空的
      let userId = storesUserInfo.userInfos.id
      if (userId == null || userId === ''){
        const res = getCurrentUserInfo()
        userId = res.data.userId
      }

      // console.log(state.fileData.userId,"state.fileData.userId")
      // console.log(userId,"userId")

      data = isShareUser(userId) //判断是否存在于共享列表中,不在返回null

      if (data == null){
        if(state.fileData.userId === userId){
          //判断文档创建人是否为自己
          isEdit.value = true
          mode.value = "edit"
          console.log("打开自己的文档")
          return
        }else{
          //不存在邀请列表中 同时 不是自己的文档 那他是怎么进来的?
          //建议封了
          isNoAccess()
        }
      }else{
        //存在邀请列表中 进入下一步判断...
      }

      // 完全操作权限-Full Access,只读权限-Read Only 拒绝访问-Deny Access
      //有点rz写的 但是后期可能好维护点
      switch (state.docAuthority){
        case 0:
          if(data.permissions === 'Full Access'){
            isEdit.value = true
            mode.value = "edit"
          }else if(data.permissions === 'Read Only'){
            isEdit.value = false
          }else{
            isNoAccess()
          }
          break; //公共读写 需要判断用户权限
        case 1:
          isEdit.value = false
          if(data.permissions === 'Deny Access'){
            isNoAccess()
          }
          break; //公共读 需要判断用户权限
        case 2:
          //data为null时 证明不在邀请范围内
          if(data == null){
            isNoAccess()
          }else{
            console.log(data,"case:2")
            if(data.permissions === 'Full Access'){
              isEdit.value = true
              mode.value = "edit"
            }else if(data.permissions === 'Read Only'){
              isEdit.value = false
            }else{
              isNoAccess()
            }
          }
          break; //仅邀请 需要判断用户权限
        case 3:
          isNoAccess()
          break; //私密的
        default: isNoAccess();
      }
    }
    //判断是否存在于分享人中
    const isShareUser = (userId) => {
      if (state.fileData.invite != null){
        for (let i = 0; i < state.fileData.invite.length; i++) {
          if(state.fileData.invite[i].id === userId){
            return state.fileData.invite[i]
          }
        }
      }
      return null
    }
    //路由返回上一级
    const back = () => {
      router.go(-1)
    }
    //刷新页面
    const refresh = () => {
      router.go(0)
    }
    //判断是否拒绝访问 方法体内userId为null时直接拒绝访问
    const isNoAccess = (userId) => {
      if(state.fileData.userId !== userId){
        state.noAccess = true
        ElMessageBox.confirm(
            '当前文档拒绝访问',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
        ).then(() => {
          back()
        }).catch(()=> {
          back()
        })
      }
    }

    onMounted(  async () => {
      apiUrl.value = import.meta.env.VITE_API_URL

      let storesCooperate = cooperateStates()
      let fileSuffix = storesCooperate.title.split(".").pop();
      state.currentFileLogId = storesCooperate.fileLogId
      let documentType = getDocumentType(fileSuffix)

      //获取权限数据
      let res = await getByFileLogId(storesCooperate.fileLogId)
      state.docAuthority = res.data.docAuthority
      if (res.data.invite !== null && res.data.invite !== '') {
        res.data.invite = res.data.invite.replace(/\\"/g, '"');
        res.data.invite = JSON.parse(res.data.invite);
      }
      state.fileData = res.data
      userAuthority()

      //TODO 如果docKey为空必须禁止进入 否则概率出现文档错误覆盖(严重)
      if(res.data.documentKey == null || res.data.documentKey === ""){
        ElMessageBox.confirm(
            '当前文档正在保存中,请重新进入',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
        ).then(() => {
          refresh()
        }).catch(()=> {
          back()
        })
        return;
      }

      state.config = {
        document: {
          fileType: fileSuffix.toLowerCase(),
          key: res.data.documentKey,
          title: storesCooperate.title,
          url: storesCooperate.fileVisitSite,
          permissions: {
            // 权限控制
            // fillForms: true,
            comment: false, // 评论功能的开关
            chat: true, // 聊天内容开关
            copy: true, // 允许复制内容
            download: true, // 是否允许下载（其实就是另存为，因为保存就是保存在服务器）
            edit: isEdit.value, // 是否允许编辑文档 isEdit.value
            print: true, // 是否允许打印
            review: true, // 可编辑时才可用，功能没试过，应该是协同编辑下的评审
            save: true,
            deleteCommentAuthorOnly: true, // 仅允许删除其注释
            editCommentAuthorOnly: true, // 仅允许编辑其注释
            protect: false, // 定义工具栏上的保护菜单是否显示
          },
          info: {
            owner: storesCooperate.owner, //文件创建者名称
            sharingSettings:[],
            uploaded: storesCooperate.uploadTime //文件创建时间
          },
        },
        type: isMobile() ? "mobile" : "desktop",  //desktop：桌面   mobile：移动端  embedded：嵌入网页
        documentType: documentType,  //word  cell   slide
        editorConfig: {
          mode: mode.value,
          lang: "zh",
          callbackUrl: apiUrl.value + "work-file-attach/collaborative/callBack?fileVisitSite=" + storesCooperate.fileVisitSite + "&fileLogId=" + storesCooperate.fileLogId,
          user: {
            id: Cookies.get('userId'),
            name: Cookies.get('userName'),
          },
          //Embedded部分仅适用于嵌入式文档类型（请参阅config部分以了解如何定义嵌入式文档类型）。它允许更改设置，这些设置定义嵌入式模式下按钮的行为。
          embedded: {
            embedUrl: state.serverUrl + "embedded?doc=" + storesCooperate.compileFileName, //定义文档的绝对URL，以作为嵌入到网页中的文档的源文件
            fullscreenUrl: state.serverUrl + "embedded?doc=+" + storesCooperate.compileFileName + "+#fullscreen", //定义将以全屏模式打开的文档的绝对URL。
            shareUrl: state.serverUrl + "view?doc=" + storesCooperate.compileFileName, //定义允许其他用户共享此文档的绝对URL。
            toolbarDocked: "top" //定义嵌入式查看器工具栏的位置，可以为top或bottom。
          },
          customization: {
            plugins: false, //禁用插件
            customer: {
              address: "广州番禺区南浦",
              info: "17工作网",
              logo: "/src/assets/project.svg",
              logoDark: "https://example.com/dark-logo-big.png",
              mail: "17work@gmail.com",
              name: "Omnitrix",
              phone: "123456789",
              www: "17work.com"
            },
            // logo: { //只有专业版 给钱才能改
            //   image: "https://17work-1304122643.cos.ap-guangzhou.myqcloud.com/17work/0/20230919/C0037AF8F01A471EAFCE5EC848EB62B7.SVG", //修改左上角的logo图片
            //   imageDark: "https://17work-1304122643.cos.ap-guangzhou.myqcloud.com/17work/0/20230919/C0037AF8F01A471EAFCE5EC848EB62B7.SVG", //深色模式
            //   url:"https://www.phphwo.cn"
            // },
          },
          features: {
            spellcheck: {
              mode: false,
              change: false
            }
          },
          // 定义共享编辑模式（快速fast/严格strict）, change为控制是否允许修改
          coEditing: {
            mode: "fast",
            change: false
          }
        }
      }

      //在权限中显示
      if (res.data.invite){
        res.data.invite.forEach(item =>{
          state.config.document.info.sharingSettings.push(
              {
                permissions: item.permissions === 'Full Access' ? "完全操作权限" : item.permissions === 'Read Only' ? "只读权限" : "拒绝访问",
                user: item.user,
                id:item.id
              }
          )
        })
      }

      if(!state.noAccess){
        state.isShow = true //打开组件,开始渲染
      }

    })
    return{
      ...toRefs(state),
      DocumentEditor,
      CooperateAuthority,
      ElMessageBox,
      storesUserInfo,
      apiUrl,
      router,
      fileData,
      storesCooperate,
      isEdit,
      mode,
      onDocumentReady,
      onRequestSharingSettings,
      userAuthority,
      isShareUser,
      back,
      isNoAccess,
      refresh,

    }
  },
}
</script>

<style scoped>

</style>
